package com.hzit.user.controller;

import com.hzit.user.dto.UserDTO;
import com.hzit.user.service.IUserService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.JsonPath;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wf
 * @since 2024-03-20
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IUserService userService;

	//1. 欢迎页面
	@GetMapping({"/","/register.html"})
	public String index(Model model){
		return "register";
	}

	//2. 查询所有用户 (lua + redis实现分布式锁)
	@GetMapping("/list")
	@ResponseBody
	public R list(){
		List<User> userList = userService.findAll();
		return R.ok();
	}
	//3. 查询所有用户 (redisson实现分布式锁)
	@GetMapping("/list2")
	@ResponseBody
	public R list2(){
		List<User> userList = userService.findAll2();
		return R.ok(userList);
	}
	//2. 生成验证码
	@GetMapping("/user/createCode/{phone}")
	public String createCode(@PathVariable("phone") String phone){
		userService.createCode(phone);
		return "register";
	}
	//3. 根据id查询用户
	@ResponseBody
	@GetMapping("/findById/{id}")
	public R findById(@PathVariable("id") Long id){
		return R.ok(userService.getById(id));
	}

	//3. 注册用户
	@PostMapping("/user/add")
	public String add(UserDTO dto,Model model){
		boolean b = userService.add(dto);
		if(!b){
			throw new RuntimeException("对不起，验证码输入有误！");
			// model.addAttribute("error","对不起，验证码输入有误！");
			// return "register_error";
		}
		return "register";
	}

	//4. 添加用户（分布式事务测试）
	@PostMapping("/save")
	@ResponseBody
	public R save(){
		userService.saveUser();
		return R.ok();
	}
}
